package com.itheima.web.controller.report;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet("/report/reportForm")
public class ReportFormServlet extends BaseServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            findAll(req, resp);
        } else if ("reFind".equals(operation)) {
            reFindAll(req, resp);
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("/WEB-INF/pages/report/list.jsp").forward(req, resp);


    }

    private void reFindAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int year = Integer.parseInt(req.getParameter("year"));
        List<Map> memberReport = reportFormService.memberReport(year);
        int[] arr = new int[12];
        for (int i = 0; i < memberReport.size(); i++) {
            Map map = memberReport.get(i);
            System.out.println(map);
            Integer month = (Integer) map.get("MONTH");
            long countL = (long) map.get("COUNT");
            int count = (int) countL;
            arr[month-1] = count;
        }
        System.out.println(Arrays.toString(arr));
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(arr);
        resp.getWriter().write(json);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
